<template>
  <div class="app-container">
    <el-form :model="form" size="small" label-position="left" ref="form" :rules="rules" class="password-form-container" label-width="100px">
      <el-form-item size="small" label="旧密码" prop="oldPassword">
        <el-input size="small" type="password" auto-complete="off" class="shop-form-input" v-model="form.oldPassword"></el-input>
      </el-form-item>
      <el-form-item size="small" label="新密码" prop="newPassword">
        <el-input size="small" type="password" auto-complete="off" class="shop-form-input" v-model="form.newPassword"></el-input>
      </el-form-item>
      <el-form-item size="small" label="确认密码" prop="rePassword">
        <el-input size="small" type="password" auto-complete="off" class="shop-form-input" v-model="form.rePassword"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain  @click="submitForm('form')">确 认</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import { changePassword } from '../../../api/index'

  export default {
    components: {
    },
    data() {
      const validatePass1 = (rule, value, callback) => {
        if (this.form.rePassword) {
          this.$refs['form'].validateField('rePassword')
        }
        callback()
      }
      const validatePass2 = (rule, value, callback) => {
        if (value !== this.form.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      }
      return {
        form: {},
        rules: {
          oldPassword: [
            { required: true, message: '请输入旧密码', trigger: 'blur' },
            { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
          ],
          newPassword: [
            { required: true, message: '请输入新密码', trigger: 'blur' },
            { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
            { validator: validatePass1, trigger: 'blur' }
          ],
          rePassword: [
            { required: true, message: '请输入确认密码', trigger: 'blur' },
            { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
            { validator: validatePass2, trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      submitForm(formName) {
        console.log(this.form)
        this.$refs[formName].validate((valid) => {
          if (valid) {
            changePassword(this.form).then(res => {
              this.$message({ type: 'success', message: '修改成功' })
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    }
  }
</script>
